class Post < ActiveRecord::Base
  
  attr_accessible :title, :raw_body, :published_at, :tag_string, :published, :comments_enabled, :comments_disabled_after
  
  # plugins
  acts_as_blog
  acts_as_taggable
  cattr_reader :per_page
  @@per_page = 6 
  has_friendly_id :title, :use_slug => true
  
  belongs_to :user
  has_many :comments
  belongs_to :asset
  
  validates_format_of :tag_string, :with => /^[A-Za-z0-9\ \,]*$/
  validates_format_of :title, :with => /^[^\<\>]*$/
  
  validates_presence_of :title, :raw_body
  validates_uniqueness_of :title  # makes our slugs unique,  not absolutely required
  
  def before_create
    self.published_at = Time.now unless self.published_at  
  end
  
  def after_destroy
    Comment.delete_all("post_id = #{self.id}")
    Asset.delete_all("id = #{self.asset_id}") if self.asset_id
  end
  
  def before_save
    self.body = Post.convert_to_html(self.raw_body, 'markdown')
    logger.info "ID: #{self.user_id}"
  end
  
  # Get a list of all the posts by months & years
  def self.count_by_months
    dates = {} 
    post_times = Post.find(:all, :select => "published_at", :conditions => "published = true")
    for post in post_times    
      year = post.published_at.year.to_s
      month = post.published_at.strftime("%b").intern
      dates[year] ||= {} 
      dates[year][month] ||= 0
      dates[year][month] += 1
      dates[year][:total] ||= 0
      dates[year][:total] += 1
    end
    dates
  end
  
  # Count posts on a certain date
  def self.count_by_date(year, month = nil, day = nil, limit = nil)
    if !year.blank?
      from, to = self.time_delta(year, month, day)
      Post.count(["published_on BETWEEN ? AND ? AND published = ?", from, to, true])
    else
      Post.count(:conditions => { :published => true })
    end
  end
  
  # Find posts on a certain date
  def self.find_by_date(year, month = nil, day = nil, limit = nil)
    if !year.blank?
      from, to = self.time_delta(year, month, day)
      Post.find(:all, :order => "published_at DESC", 
                :conditions => ["published_at BETWEEN ? AND ? AND published = ?", from, to, true])
    end
  end
  
  # Utility function (thanks typo!)
  def self.time_delta(year, month = nil, day = nil)
    from = Time.mktime(year, month || 1, day || 1)

    to = from.next_year
    to = from.next_month unless month.blank?
    to = from + 1.day unless day.blank?
    to = to - 1 # pull off 1 second so we don't overlap onto the next day
    return [from, to]
  end
  
  
  # Tagging
  def tag_string=(tags)
    for tag in tags.split(" ")
      self.tag_list.push(tag.gsub(/[^A-Za-z]/, '').capitalize)
    end
  end
  
  def tag_string
    self.tag_list
  end
  

end
